package com.cljz.peipei.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cljz.peipei.R;
import com.cljz.peipei.base.App;
import com.cljz.peipei.base.BaseActivity;
import com.cljz.peipei.model.net.bean.EmojiWordBean;
import com.cljz.peipei.model.net.bean.GetUserInfoBean;
import com.cljz.peipei.model.net.bean.ResponseBean;
import com.cljz.peipei.model.net.bean.TagListBean;
import com.cljz.peipei.present.activity.MainP;
import com.cljz.peipei.ui.adapter.HaveChosenAdapter;
import com.cljz.peipei.utils.CommonUtils;
import com.cljz.peipei.utils.L;
import com.cljz.peipei.utils.T;
import com.cljz.peipei.widget.CameraSurfaceView;
import com.cljz.peipei.widget.FlagButton;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMCallManager;
import com.hyphenate.chat.EMCallStateChangeListener;
import com.hyphenate.chat.EMChatManager;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.EMNoActiveCallException;
import com.hyphenate.exceptions.EMServiceNotReadyException;
import com.hyphenate.media.EMLocalSurfaceView;
import com.hyphenate.media.EMOppositeSurfaceView;
import com.hyphenate.util.NetUtils;
import com.jakewharton.rxbinding.view.RxView;
import com.superrtc.sdk.VideoView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.router.Router;
import pl.droidsonroids.gif.GifImageView;
import rx.functions.Action1;

/**
 * Created by apple on 2017/4/19.
 */

public class MainActivity extends BaseActivity<MainP> implements EMCallBack, EMConnectionListener, UMShareListener, RadioGroup.OnCheckedChangeListener, FlagButton.OnFlagItemClick, HaveChosenAdapter.OnItemClickListener, EMMessageListener, EMCallStateChangeListener {

    private static final int CALL_WAIT = 233;
    private static final int CUT_EMOJI = 1;
    private String waitType;

    @BindView(R.id.iv_setting)
    ImageView ivSetting;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.iv_label)
    ImageView ivLabel;
    @BindView(R.id.csv_camera)
    CameraSurfaceView csvCamera;
    @BindView(R.id.tv_emoji)
    TextView tvEmoji;
    @BindView(R.id.opposite_surface)
    EMOppositeSurfaceView oppositeSurface;
    @BindView(R.id.local_surface)
    EMLocalSurfaceView localSurface;
    @BindView(R.id.tv_count_down)
    TextView tvCountDown;
    @BindView(R.id.ll_local)
    LinearLayout llLocal;
    @BindView(R.id.fl_main)
    FrameLayout flMain;
    private PopupWindow settingWindow;
    private PopupWindow shareWindow;
    private List<TagListBean.DataBean.tagBean> myTagList;
    private List<TagListBean.DataBean.tagBean> otherTagList;
    private PopupWindow tagsWindow;
    private int matchingSex = 3;
    private HaveChosenAdapter haveChosenAdapter;
    private Handler mainHandler;
    private List<EmojiWordBean.DataBean> emojiWordList;
    private PopupWindow waitWindow;
    private CallReceiver callReceiver;
    private EMCallManager.EMVideoCallHelper callHelper;
    private AudioManager audioManager;
    // 音频池
    private SoundPool soundPool;
    // 声音资源 id
    private int streamID;
    private int loadId;
    private boolean isLoaded = false;
    // 记录通话方向，是呼出还是呼入
    private boolean isInComingCall = true;


    @Override
    protected void setScreen() {
        //WindowManager是Android中一个重要的服务（Service ）。WindowManager Service 是全局的，是唯一的
        //WindowManager.LayoutParams 是 WindowManager 接口的嵌套类；它继承于 ViewGroup.LayoutParams；
        // 它用于向WindowManager描述Window的管理策略。
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        //窗口显示时，隐藏所有的屏幕装饰（例如状态条）。使窗口占用整个显示区域。
        lp.flags = (WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(lp);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        //// 设置通话界面属性，保持屏幕常亮，关闭输入法，以及解锁
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        //调用了音频池
        initSoundPool();
        audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        audioManager.setMicrophoneMute(false);
        getP().emojiWord();
        haveChosenAdapter = new HaveChosenAdapter(this, myTagList);
        getP().getTagList();
        callHelper =EMClient.getInstance().callManager().getVideoCallHelper();

        EMClient.getInstance().callManager().setSurfaceView(localSurface, oppositeSurface);
        oppositeSurface.setScaleMode(VideoView.EMCallViewScaleMode.EMCallViewScaleModeAspectFill);
        localSurface.setScaleMode(VideoView.EMCallViewScaleMode.EMCallViewScaleModeAspectFill);
        IntentFilter callFilter = new IntentFilter(EMClient.getInstance().callManager().getIncomingCallBroadcastAction());
        callReceiver = new CallReceiver();
        registerReceiver(callReceiver, callFilter);



    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public MainP newP() {
        return new MainP();
    }

    @Override
    protected void onStart() {
        super.onStart();
        EMClient.getInstance().login(getP().getUserInfo(getP().getToken()).getUser_id(), getP().getUserInfo(getP().getToken()).getUser_id(), this);
        EMClient.getInstance().callManager().addCallStateChangeListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (shareWindow != null && shareWindow.isShowing()) {
            shareWindow.dismiss();
        }
        if (settingWindow != null && settingWindow.isShowing()) {
            settingWindow.dismiss();
        }
        if (tagsWindow != null && tagsWindow.isShowing()) {
            ////关闭popWindow
            tagsWindow.dismiss();
        }
        EMClient.getInstance().chatManager().removeMessageListener(this);
        EMClient.getInstance().logout(true, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mainHandler) {
            //如果参数为null的话，会将所有的Callbacks和Messages全部清除掉。
            //在Acticity退出的时候，可以避免内存泄露。
            mainHandler.removeCallbacksAndMessages(null);
        }
        unregisterReceiver(callReceiver);
        EMClient.getInstance().chatManager().removeMessageListener(this);
        EMClient.getInstance().logout(true, this);
//        localSurface.getRenderer().dispose();
//        localSurface = null;
//        oppositeSurface.getRenderer().dispose();
//        oppositeSurface = null;
    }

    @Override
    protected void initListener() {
        super.initListener();
        EMClient.getInstance().addConnectionListener(this);
        RxView.clicks(ivSetting)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        initSetting();
                    }
                });
        RxView.clicks(ivShare)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        initShareWindow();
                    }
                });

        RxView.clicks(ivLabel)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        initTags();
                    }
                });
    }

    //设置标签
    private void initTags() {
        View tagsView = LayoutInflater.from(this).inflate(R.layout.pop_tags, null);
        RecyclerView rvHaveChosen = (RecyclerView) tagsView.findViewById(R.id.rv_have_chosen);
        FlagButton fbTags = (FlagButton) tagsView.findViewById(R.id.fb_tags);
        FrameLayout flClose = (FrameLayout) tagsView.findViewById(R.id.fl_close);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvHaveChosen.setLayoutManager(linearLayoutManager);
//        haveChosenAdapter = new HaveChosenAdapter(this, myTagList);
        rvHaveChosen.setAdapter(haveChosenAdapter);
        tagsWindow = new PopupWindow(tagsView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        tagsWindow.setTouchable(true);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        tagsWindow.setBackgroundDrawable(dw);
        tagsWindow.showAtLocation(csvCamera, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
        List<String> tagList = new ArrayList<>();
        if (otherTagList != null) {
            for (int i = 0; i < otherTagList.size(); i++) {
                tagList.add(otherTagList.get(i).getTag_name());
            }
            fbTags.initChildViews(tagList, this);
        }
        //上面跑完了，下面重新载入
        RxView.clicks(flClose)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        tagsWindow.dismiss();
                    }
                });
        haveChosenAdapter.setOnItemClickListener(this);
    }

    /**
     * 加载分享popupWindow
     */
    private void initShareWindow() {
        View shareView = LayoutInflater.from(this).inflate(R.layout.pop_share, null);
        LinearLayout llQQShare = (LinearLayout) shareView.findViewById(R.id.ll_qq_share);
        LinearLayout llZoneShare = (LinearLayout) shareView.findViewById(R.id.ll_zone_share);
        if (shareWindow == null) {
            shareWindow = new PopupWindow();
        }
        shareWindow.setContentView(shareView);
        shareWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
        shareWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        shareWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        shareWindow.setFocusable(true);
        shareWindow.setOutsideTouchable(true);
        shareWindow.setTouchable(true);
        //更新PopupWindow状态，如果当前已是显示状态，就从当前状态更新
        shareWindow.update();
        shareWindow.showAsDropDown(ivShare, Kits.Dimens.dpToPxInt(this, -55), Kits.Dimens.dpToPxInt(this, 10));
        RxView.clicks(llQQShare)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        initShare(SHARE_MEDIA.QQ);
                    }
                });
        RxView.clicks(llZoneShare)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        initShare(SHARE_MEDIA.QZONE);
                    }
                });

    }

    private void initShare(SHARE_MEDIA media) {
        UMWeb shareWeb = new UMWeb(getP().getUserInfo(getP().getToken()).getDownload());
        shareWeb.setTitle("配配");
        shareWeb.setDescription("随时随地发现有缘人");
        new ShareAction(this)
                .setPlatform(media)
                .setCallback(this)
                .withMedia(shareWeb)
                .share();
        shareWindow.dismiss();
    }

    /**
     * 加载设置popupWindow
     */
    private void initSetting() {
        View settingView = LayoutInflater.from(this).inflate(R.layout.pop_setting, null);
        ImageView ivClose = (ImageView) settingView.findViewById(R.id.iv_close);
        RelativeLayout rlReturn = (RelativeLayout) settingView.findViewById(R.id.rl_return);
        RelativeLayout rlSex = (RelativeLayout) settingView.findViewById(R.id.rl_sex);
        RadioGroup rgSex = (RadioGroup) settingView.findViewById(R.id.rg_sex);
        FrameLayout flClose = (FrameLayout) settingView.findViewById(R.id.fl_close);
        settingWindow = new PopupWindow(settingView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        settingWindow.setTouchable(true);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        settingWindow.setBackgroundDrawable(dw);
        settingWindow.showAtLocation(csvCamera, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
        RxView.clicks(flClose)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        settingWindow.dismiss();
                    }
                });
        RxView.clicks(ivClose)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        settingWindow.dismiss();
                    }
                });
        RxView.clicks(rlReturn)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .to(SetSexActivity.class)
                                .launch();
                        settingWindow.dismiss();
                    }
                });
        rgSex.setOnCheckedChangeListener(this);

    }


    @Override
    public void onSuccess() {
        EMClient.getInstance().groupManager().loadAllGroups();
        EMClient.getInstance().chatManager().loadAllConversations();
        EMClient.getInstance().chatManager().addMessageListener(this);
        getP().callEnd();
        L.e("main", "登录聊天服务器成功！");
    }

    @Override
    public void onError(int i, String s) {
        L.e("main", "登录聊天服务器失败！");
    }

    @Override
    public void onProgress(int i, String s) {

    }

    @Override
    public void onConnected() {

    }

    @Override
    public void onDisconnected(final int error) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (error == EMError.USER_REMOVED) {
                    // 显示帐号已经被移除
                    L.e("main", "帐号已经被移除！");
                } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                    // 显示帐号在其他设备登录
                    L.e("main", "帐号在其他设备登录！");
                } else if (NetUtils.hasNetwork(MainActivity.this)) {
                    //连接不到聊天服务器
                    L.e("main", "连接不到聊天服务器！");
                } else {
                    //当前网络不可用，请检查网络设置
                    L.e("main", "当前网络不可用，请检查网络设置！");
                }
            }
        });
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {

    }

    @Override
    public void onResult(SHARE_MEDIA share_media) {
        shareResult(share_media, "分享成功");

    }

    @Override
    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
        shareResult(share_media, "分享失败");

    }

    @Override
    public void onCancel(SHARE_MEDIA share_media) {
        shareResult(share_media, "取消分享");

    }

    private void shareResult(SHARE_MEDIA share_media, String msg) {
        if (SHARE_MEDIA.QQ.equals(share_media)) {
            T.getInstance().showShort("QQ" + msg);
        } else if (SHARE_MEDIA.QZONE.equals(share_media)) {
            T.getInstance().showShort("QQ空间" + msg);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    public void getUserInfoSucceed(GetUserInfoBean getUserInfoBean) {
        initWaitWindow(getUserInfoBean);
    }

    //聊天主要逻辑
    private void initWaitWindow(GetUserInfoBean getUserInfoBean) {
        View waitView = View.inflate(this, R.layout.pop_video_call, null);
        LinearLayout llBtn = (LinearLayout) waitView.findViewById(R.id.ll_btn);
        TextView tvOverlook = (TextView) waitView.findViewById(R.id.tv_overlook);
        Button btnJoinUp = (Button) waitView.findViewById(R.id.btn_join_up);
        GifImageView givWait = (GifImageView) waitView.findViewById(R.id.giv_wait);
        LinearLayout llTags = (LinearLayout) waitView.findViewById(R.id.ll_tags);
        TextView tvTag1 = (TextView) waitView.findViewById(R.id.tv_tag1);
        TextView tvTag2 = (TextView) waitView.findViewById(R.id.tv_tag2);
        TextView tvTag3 = (TextView) waitView.findViewById(R.id.tv_tag3);
        TextView tvDescribe = (TextView) waitView.findViewById(R.id.tv_describe);
        TextView tvNickname = (TextView) waitView.findViewById(R.id.tv_nickname);
        ImageView ivSex = (ImageView) waitView.findViewById(R.id.iv_sex);
        if ("initiate".equals(waitType)) {
            llBtn.setVisibility(View.GONE);
            givWait.setVisibility(View.VISIBLE);
            csvCamera.setVisibility(View.GONE);
        } else {
            llBtn.setVisibility(View.VISIBLE);
            givWait.setVisibility(View.GONE);
        }
        tvNickname.setText(getUserInfoBean.getData().getNickname());
        List<String> tags = getUserInfoBean.getData().getTag();
        if (tags.size() == 0) {
            llTags.setVisibility(View.GONE);
        } else {
            if (tags.size() == 1) {
                llTags.setVisibility(View.VISIBLE);
                tvTag1.setText(tags.get(0));
                tvTag2.setVisibility(View.GONE);
                tvTag3.setVisibility(View.GONE);
            } else if (tags.size() == 2) {
                llTags.setVisibility(View.VISIBLE);
                tvTag1.setText(tags.get(0));
                tvTag2.setText(tags.get(1));
                tvTag3.setVisibility(View.GONE);
            } else {
                llTags.setVisibility(View.VISIBLE);
                tvTag1.setText(tags.get(0));
                tvTag2.setText(tags.get(1));
                tvTag3.setText(tags.get(2));
            }
        }
        if ("1".equals(getUserInfoBean.getData().getSex())) {
            attemptPlayCallSound();
            ivSex.setImageResource(R.mipmap.male);
            tvDescribe.setText("有一位" + getUserInfoBean.getData().getAge() + "岁的小哥哥正在向你招手");
        } else if ("0".equals(getUserInfoBean.getData().getSex())) {
            attemptPlayCallSound();
            ivSex.setImageResource(R.mipmap.female);
            tvDescribe.setText("有一位" + getUserInfoBean.getData().getAge() + "岁的美少女正在向你招手");
        }
        RxView.clicks(tvOverlook)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        //拒绝接听
                        try {
                            stopCallSound();
                            EMClient.getInstance().callManager().rejectCall();
                        } catch (EMNoActiveCallException e) {
                            e.printStackTrace();
                        }
                        waitWindow.dismiss();
                        csvCamera.setVisibility(View.VISIBLE);
                    }
                });
        RxView.clicks(btnJoinUp)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        //接听通话
                        try {
                            openSpeakerOn();
                            stopCallSound();
                            EMClient.getInstance().callManager().answerCall();
                        } catch (EMNoActiveCallException e) {
                            e.printStackTrace();
                        }
                        EMClient.getInstance().callManager().setSurfaceView(localSurface, oppositeSurface);
                        waitWindow.dismiss();
                    }
                });

        waitWindow = new PopupWindow(waitView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        waitWindow.setTouchable(true);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        waitWindow.setBackgroundDrawable(dw);
        waitWindow.showAtLocation(flMain, 0, 0, 0);
    }

    public void getUserInfoFail(String error) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_girl:
                matchingSex = 2;
                break;
            case R.id.rb_boy:
                matchingSex = 1;
                break;
            case R.id.rb_all:
                matchingSex = 3;
                break;
        }
    }

    public void getTagListSucceed(TagListBean tagListBean) {
        myTagList = tagListBean.getData().getMy();
        otherTagList = tagListBean.getData().getOther();
        haveChosenAdapter.setMyTagList(myTagList);
        beginCallWait();
    }

    public void beginCallWait() {
        int size = myTagList.size();
        if (size > 0) {
            StringBuilder myTags = new StringBuilder();
            for (int i = 0; i < size; i++) {
                myTags.append(myTagList.get(i).getId());
                if (size - 1 != i) {
                    myTags.append(",");
                }
            }
            getP().callWait(matchingSex, myTags.toString());
        } else {
            getP().callWait(matchingSex, "");
        }
    }

    public void getTagListFail(String error) {

    }

    @Override
    public void OnItemClick(int position) {
        if (myTagList.size() >= 3) {
            T.getInstance().showShort("最多可以添加三个标签哦");
        } else {
            if (!myTagList.contains(otherTagList.get(position))) {
                myTagList.add(otherTagList.get(position));
                haveChosenAdapter.setMyTagList(myTagList);
                getP().tagSet(otherTagList.get(position).getId());
            } else {
                T.getInstance().showShort("已添加过该标签");
            }
        }
    }

    public void getTagSetSucceed(ResponseBean responseBean) {

    }

    public void getTagSetFail(String error) {

    }

    @Override
    public void onClick(TagListBean.DataBean.tagBean dataBean) {
        myTagList.remove(dataBean);
        haveChosenAdapter.setMyTagList(myTagList);
        getP().tagDel(dataBean.getId());
    }

    @Override
    public void onLongClick(TagListBean.DataBean.tagBean dataBean) {

    }

    public void getTagDelSucceed(ResponseBean responseBean) {

    }

    public void getTagDelFail(String error) {

    }


    public void getEmojiWordSucceed(EmojiWordBean emojiWordbean) {
        emojiWordList = emojiWordbean.getData();
        if (emojiWordList.size() != 0) {
            mainHandler = new MainHandler(this);
            mainHandler.sendEmptyMessageDelayed(CUT_EMOJI, 10000);
            tvEmoji.setText(emojiWordList.get(0).getContent());
        }

    }

    public void getEmojiWordFail(String error) {

    }

    public TextView getTvEmoji() {
        return tvEmoji;
    }

    public List<EmojiWordBean.DataBean> getEmojiWordList() {
        return emojiWordList;
    }

    public void callWaitSucceed(ResponseBean responseBean) {
        mainHandler.sendEmptyMessageDelayed(CALL_WAIT, 10000);
    }

    public void callWaitFail(String error) {
        mainHandler.sendEmptyMessageDelayed(CALL_WAIT, 10000);

    }

    /**
     * 通话监听
     *
     * @param callState
     * @param callError
     */
    @Override
    public void onCallStateChanged(CallState callState, CallError callError) {
        switch (callState) {
            case CONNECTING: // 正在连接对方

                break;
            case CONNECTED: // 双方已经建立连接

                break;

            case ACCEPTED: // 电话接通成功
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (waitWindow != null&& waitWindow.isShowing()) {
                            waitWindow.dismiss();
                        }
                        csvCamera.setVisibility(View.GONE);
                        llLocal.setVisibility(View.VISIBLE);
                        localSurface.setZOrderMediaOverlay(true);
                        localSurface.setZOrderOnTop(true);
                        openSpeakerOn();
                    }
                });
                break;
            case DISCONNECTED: // 电话断了，这里需要再次调用自己的接口
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        llLocal.setVisibility(View.GONE);
                        csvCamera.setVisibility(View.VISIBLE);
                    }
                });
                break;
            case NETWORK_UNSTABLE: //网络不稳定
                if (callError == CallError.ERROR_NO_DATA) {
                    //无通话数据
                } else {
                }
                break;
            case NETWORK_NORMAL: //网络恢复正常

                break;
            default:
                break;
        }

    }

    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        //收到消息
        L.e("收到消息");
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        //收到透传消息
        L.e("收到透传消息");
        for (int i = 0; i < messages.size(); i++) {
            L.e(messages.get(i).getBody().toString());
        }
        String otherUserId = CommonUtils.getNumbers(messages.get(0).getBody().toString());
        L.e(otherUserId);
        waitType = "initiate";
        try {
            //视频如果不是对方打来的，就主动呼叫
            EMClient.getInstance().callManager().makeVideoCall(otherUserId);
            EMClient.getInstance().callManager().setSurfaceView(localSurface, oppositeSurface);
        } catch (EMServiceNotReadyException e) {
            e.printStackTrace();
        }
        getP().getUserInfoData(otherUserId);

    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {
        L.e("收到已读回执");
        //收到已读回执
    }

    @Override
    public void onMessageDelivered(List<EMMessage> message) {
        //收到已送达回执
    }

    @Override
    public void onMessageChanged(EMMessage message, Object change) {
        //消息状态变动
        L.e("消息状态变动");

    }

    public void callEndSucceed(ResponseBean responseBean) {

    }

    public void callEndFail(String error) {

    }


    private static class MainHandler extends Handler {
        private final WeakReference<MainActivity> mActivity;
        private int position = 1;
        List<EmojiWordBean.DataBean> emojiWordBeenList;

        MainHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
            emojiWordBeenList = activity.getEmojiWordList();
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();
            switch (msg.what) {
                case CUT_EMOJI:
                    if (position == emojiWordBeenList.size() - 1) {
                        position = 0;
                    }
                    activity.getTvEmoji().setText(emojiWordBeenList.get(position).getContent());
                    this.sendEmptyMessageDelayed(CUT_EMOJI, 10000);
                    position++;
                    break;
                case CALL_WAIT:
                    activity.beginCallWait();
                    break;
            }
        }
    }
    IntentFilter callFilter = new IntentFilter(EMClient.getInstance().callManager().getIncomingCallBroadcastAction());

    // registerReceiver(new CallReceiver(),callFilter);

    private class CallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 拨打方username
            String from = intent.getStringExtra("from");
            // call type
            String type = intent.getStringExtra("type");
            //跳转到通话页面
            L.e(from);
            waitType = "receive";
            getP().getUserInfoData(from);
        }
    }
    // 打开扬声器
    protected void openSpeakerOn() {
        try {
            if (!audioManager.isSpeakerphoneOn()){
                // 打开扬声器
                audioManager.setSpeakerphoneOn(true);}
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void closeSpeakerOn() {

        try {
            if (audioManager != null) {
                // int curVolume =
                // audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
                if (audioManager.isSpeakerphoneOn()){
                    audioManager.setSpeakerphoneOn(false);
                }
                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                // audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                // curVolume, AudioManager.STREAM_VOICE_CALL);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * ----------------------------- 音频池Sound start -----------------------------
     * 初始化 SoundPool
     */
    private void initSoundPool() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes attributes = new AudioAttributes.Builder()
                    // 设置音频要用在什么地方，这里选择电话通知铃音
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();
            // 当系统的 SDK 版本高于21时，使用 build 的方式实例化 SoundPool
            soundPool =
                    new SoundPool.Builder().setAudioAttributes(attributes).setMaxStreams(1).build();
        } else {
            // 老版本使用构造函数方式实例化 SoundPool，MODE 设置为铃音 MODE_RINGTONE
            soundPool = new SoundPool(1, AudioManager.MODE_RINGTONE, 0);
        }
    }

    /**
     * 加载音效资源
     */
    private void loadSound() {
        if (isInComingCall) {
            loadId = soundPool.load(context, R.raw.sound_call_incoming, 1);
        } else {
            loadId = soundPool.load(context, R.raw.sound_calling, 1);
        }
    }

    /**
     * 尝试播放呼叫通话提示音
     */
    public void attemptPlayCallSound() {
        // 检查音频资源是否已经加载完毕
        if (isLoaded) {
            playCallSound();
        } else {
            // 播放之前先去加载音效
            loadSound();
            // 设置资源加载监听，也因为加载资源在单独的进程，需要时间，所以等监听到加载完成才能播放
            soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                @Override public void onLoadComplete(SoundPool soundPool, int i, int i1) {
                    isLoaded = true;
                    // 首次监听到加载完毕，开始播放音频
                    playCallSound();
                }
            });
        }
    }

    /**
     * 播放音频
     */
    private void playCallSound() {
        // 打开扬声器
       openSpeakerOn();
        // 设置音频管理器音频模式为铃音模式
        audioManager.setMode(AudioManager.MODE_RINGTONE);
        // 播放提示音，返回一个播放的音频id，等下停止播放需要用到
        if (soundPool != null) {
            streamID = soundPool.play(loadId, // 播放资源id；就是加载到SoundPool里的音频资源顺序
                    0.5f,   // 左声道音量
                    0.5f,   // 右声道音量
                    1,      // 优先级，数值越高，优先级越大
                    -1,     // 是否循环；0 不循环，-1 循环，N 表示循环次数
                    1);     // 播放速率；从0.5-2，一般设置为1，表示正常播放
        }
    }

    /**
     * 关闭音效的播放，并释放资源
     */
    protected void stopCallSound() {
        if (soundPool != null) {
            // 停止播放音效
            soundPool.stop(streamID);
            // 卸载音效
            //soundPool.unload(loadId);
            // 释放资源
            //soundPool.release();
        }
    }// --------------------------------- Sound end ---------------------------------
}
